
/* -----------------
* brief 
* 1. this is code gen by tools 
* 2. array like [a,b,c] after each field, define the ui html tag in view, 
		a for title, 
		b for show or not ,  
		c for element html tag , currently suppor : check、radio、select、input、textarea、upload tag
* 3. XXX
*/

package wechat

import (
	"saas_sys_base/common"
	"saas_sys_base/redishelper"

	//"saas_sys_base/config"
	configService "saas_sys_base/modules/config/service"
)

import (
	"github.com/chanxuehong/wechat/mp/core"

)

func init() {

}

/* table: "tb_wechat"
 * -----------------
*/
type WechatClient struct {
	appConfigService configService.AppConfigService
}

//方案二：采用appid为key，获取client
var _wxClientMap map[string]*core.Client
var _wxCheckConfigMap map[string]*common.AppConfig //用于检测是否有重复的公众号配置

func init() {
	_wxClientMap = make( map[string]*core.Client)
	_wxCheckConfigMap = make(map[string]*common.AppConfig)

	t := new(WechatClient)
	appConfigList := t.appConfigService.GetAllAppConfig()
	for _, v := range appConfigList {
		wechatConfig := v.App_Config_Data.Wechat
		if wechatConfig.WX_APPID == "" {
			continue
		}
		_, ok := _wxClientMap[wechatConfig.WX_APPID]
		if ok {
			//如果发现app对应的微信配置存在，则检查是否与前值一致，如果不一致则抛出panic
			//因为微信配置值是必须一致的，这种情况可能是手动输入配置文件时有错误
			//if prevValue.wechatConfig.WX_APPSECRET
			v2, ok2 := _wxCheckConfigMap[wechatConfig.WX_APPID]
			if !ok2 { //理论上不可能到这一个分支
				panic("check wxCheckServerMap error")
			}

			if v.App_Config_Data.Wechat.WX_APPSECRET != v2.App_Config_Data.Wechat.WX_APPSECRET ||
				v.App_Config_Data.Wechat.WX_MP_TOKEN != v2.App_Config_Data.Wechat.WX_MP_TOKEN ||
				v.App_Config_Data.Wechat.WX_MP_ENCODED_AESKey != v2.App_Config_Data.Wechat.WX_MP_ENCODED_AESKey {
				panic("there may be mistake in wechat mp config, the same mp config must be same!")
			}
			continue
		}
		_wxClientMap[wechatConfig.WX_APPID] = NewWxClient(wechatConfig.WX_APPID, wechatConfig.WX_APPSECRET)
		_wxCheckConfigMap[wechatConfig.WX_APPID]= v

	}
}

func NewWxClient(wxAppId string, wxAppSecret string) *core.Client {
    if wxAppId == "" || wxAppSecret == "" {
    	panic("wxAppId or wxAppSecret is not set")
    	return nil
	}

	AccessTokenServer := core.NewRedisAccessTokenServer(wxAppId, wxAppSecret, nil, redishelper.GetRedisConn) //支持分布式token
	//使用redis分布式token替代 AccessTokenServer := core.NewDefaultAccessTokenServer(wxAppId, wxAppSecret, nil)
	WechatClient := core.NewClient(AccessTokenServer, nil)
	return WechatClient
}



// 获取公众号api client
func (t *WechatClient) GetMpClientByWho(who common.Who) *core.Client {
	// DONE 这个函数要改为去找weappid为key的core.Client map
	config, err := t.appConfigService.GetConfigByWho(who)
	if err != nil {
		panic("panic: not found appconfig")
		return nil
	}

	wechatConfig := config.App_Config_Data.Wechat
	WechatClient, ok := _wxClientMap[wechatConfig.WX_MP_APPID]
	if !ok {
		return nil
	}

	return WechatClient
}
